package com.xjj.service.config;


import org.quartz.Scheduler;
import org.quartz.ee.servlet.QuartzInitializerListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;

/**
 * @Description 配置类
 * @Author zhangjin
 * @Date 2022/10/21 9:35
 */
@Configuration
public class QuartzConfig {
    @Autowired
    private MyJobFactory myJobFactory;

    @Autowired
    private DataSource dataSource;

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(){
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        // 配置数据源
        schedulerFactoryBean.setDataSource(dataSource);
        try {
            // 加载quartz数据源配置
            schedulerFactoryBean.setQuartzProperties(quartzProperties());
            // 自定义Job Factory，用于Spring注入
            schedulerFactoryBean.setJobFactory(myJobFactory);
            //启动时更新己存在的Job，这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了
            schedulerFactoryBean.setOverwriteExistingJobs(true);
            // 延时启动
            schedulerFactoryBean.setStartupDelay(20);
            return schedulerFactoryBean;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 加载quartz数据源配置
     *
     * @return
     * @throws IOException
     */
    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean=new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("/application.properties"));
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }

    /*
     * quartz初始化监听器
     */
    @Bean
    public QuartzInitializerListener executorListener() {
        return new QuartzInitializerListener();
    }

    @Bean(name="scheduler")
    public Scheduler scheduler(){
        return schedulerFactoryBean().getScheduler();
    }
}
